var express = require('express');
var router = express.Router();



var async = require("async");

var MongoClient = require("mongodb").MongoClient;
var DB_CONN_STR = "mongodb://127.0.0.1:27017/test";





router.get('/', function(req, res, next) {
    var pageNo = req.query.pageNo,//显示第几页，是用在导航栏url中的
    pageNo = pageNo ? pageNo : 1,
    pageSize = 3, //一页的个数
    count = 0, //传过来的数据条数
    totalPage = 0; //总的页数
    MongoClient.connect(DB_CONN_STR,(err,db)=>{
        if(err){
            res.send(err);
        }else{
            var conn = db.collection("comment");
            
            async.parallel([
                function(callback){
                    conn.find().toArray((err,result)=>{
                        totalPage = Math.ceil(result.length/pageSize);
                        count = result.length;
                        callback(null,"");
                    });
                },function(callback){
                    conn.find().sort({_id:-1})
                    .skip((pageNo-1)*pageSize)
                    .limit(pageSize).toArray((err,result)=>{
                        if(err){
                            res(err);
                        }else{
                            callback(null,result);
                        }
                    })
                }
            ],function(err,result){
                console.log(req.session.email)
                res.render("comment",{
                    list:result[1],
                    pageNo:pageNo,
                    totalPage:totalPage,
                    count:count,
                    name:req.session.email,
                })
            })
        }
    })
  });

router.post('/commentFile', function(req, res, next) {
    var title = req.body.title;
    var content = req.body.content;
    var email = req.session.email;
    console.log(email)
    if(!email){
        res.redirect("/login");
    }   
    MongoClient.connect(DB_CONN_STR,(err,db)=>{
        if(err){
            res.send(err);
        }else{
            var conn = db.collection("comment");
            var data = {title:title,content:content,email:email}
            conn.insert(data,(err)=>{
                if(err){
                    res.send(err);
                }else{
                    console.log(req.session.email )
                    res.redirect("/comment")
                };
                db.close();
            });
        }
    })
});


var multiparty = require("multiparty");
var fs = require("fs");

router.post("/uploadImg",(req,res,next)=>{
    var form = new multiparty.Form();
    form.encoding = "utf-8";//设置编码
    form.uploadDir = "./uploadtemp";//创建临时文件存储
    form.maxFilesSize = 2*1024*1024;//文件最大的大小
    form.parse(req,(err,fields,files)=>{
        if(err){
            console.log(err)
        }else{  
            var uploadurl = "./images/upload/";//设置上传图片的存放路径
            file = files['filedata'];// xhEditor规定，上传文件域的name为：filedata,获取对应的图片这个文件
            originalFilename = file[0].originalFilename;//上传文件的原始名字；
            filePath = file[0].path;//原来的文件路径
            var timeStamp = new Date().getTime();//获取当前的时间戳，以免相同名字的图片覆盖
            uploadurl += timeStamp + originalFilename;//上传图片的内容写入的路径
            newPath = './public/' + uploadurl;//设置新的路径
            //创建文件读写的文件流
            var fileReadStream = fs.createReadStream(filePath);//读取源图片内容
            var fileWriteStream = fs.createWriteStream(newPath);//写到文件中的内容
            //利用管道传送
            fileReadStream.pipe(fileWriteStream);
            fileWriteStream.on("close",()=>{
                //写入成功之后可以删除历史文件的路径
                fs.unlinkSync(filePath);
                res.send('{"err":"","msg":"'+uploadurl+'"}');
            })
        }
    })
})

// router.post('/uploadImg', function(req, res) {
//   //res.render("/login")
//   var form = new multiparty.Form();
//   //设置编码
//   form.encoding = 'utf-8';
//   //设置文件存储路径
//   form.uploadDir = './uploadtemp';
//   //设置文件大小限制
//   // form.maxFilesSize = 2 * 1024 * 1024;
//   form.parse(req,function(err,fields,files){
//       if(err){
//           console.log(err)
//       }
    //   var uploadurl = './images/upload/';
    //   file = files['filedata'];
    //   originalFilename = file[0].originalFilename; // 原始文件名
    //   tmpPath = file[0].path;

    //   var timestamp = new Date().getTime();
    //   uploadurl += timestamp + originalFilename;
    //   newPath = './public/' + uploadurl;

    //   var fileReadStream = fs.createReadStream(tmpPath);
    //   var fileWriteStream = fs.createWriteStream(newPath);
    //   fileReadStream.pipe(fileWriteStream); //管道流
    //   fileWriteStream.on('close',function(){
    //       fs.unlinkSync(tmpPath);
    //       res.send('{"err":"","msg":"'+uploadurl+'"}');
    //   })
//   });
// });


module.exports = router;